package coop.bancocredicoop.proyectos.gd.query.document;

import java.util.Date;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.Transaction;

import coop.bancocredicoop.proyectos.gd.hibernate.HibernateUtil;

public class UpdateDocumentSetDeleteFields {

	public int run(Long documentId, Date deleteDate, String deleteByUserName)
			throws Exception {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = null;
		int result = 0;

		try {
			tx = session.beginTransaction();

			result = _run(documentId, deleteDate, deleteByUserName, session);

			tx.commit();
		}
		catch (Exception e) {
			if (tx!=null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		return result;

	}

	private int _run(Long documentId, Date deleteDate, String deleteByUserName,
			Session session) throws Exception {

		Query query = session.createQuery(" UPDATE Document set " +
				" deleteDate = :deleteDate, " +
				" deleteByUserName = :deleteByUserName " +
				" where id = :id " +
				" and deleteDate is null ");
		
		query.setTimestamp("deleteDate", deleteDate);
		query.setString("deleteByUserName", deleteByUserName);
		query.setLong("id", documentId);

		return query.executeUpdate();

	}

}
